
//
//  CPJHomePageViewController.swift
//  Sina
//
//  Created by YYY on 2017/7/24.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

//定义全局变量，用private修饰，防止所有地方都能访问
//原创微博
private let originalCellId = "originalCellId"
//转发微博
private let retweetCellId = "retweetCellId"

class CPJHomePageViewController: CPJBaseViewController {
    
    //数据数组
    fileprivate lazy var homePageViewModel = CPJHomePageViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册监听者
        NotificationCenter.default.addObserver(self, selector: #selector(browserPhoto), name: NSNotification.Name(rawValue: CPJWeiboCellBrowserPhotoNotification), object: nil)

    }

    //注销通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //浏览图片
    func browserPhoto(notification: NSNotification)
    {
        //获取通知中的参数
        
        guard let selectIndex = notification.userInfo?["CPJWeiboCellBrowserPhotoSelectedIndexKey"] as? Int,
            let urls = notification.userInfo?["CPJWeiboCellBrowserPhotoUrlKey"] as? [String],
            let imageViewList = notification.userInfo?["CPJWeiboCellBrowserPhotoParentImageViewsKey"] as? [UIImageView] else
        {
            return
        }
        
        let browserVC = HMPhotoBrowserController.photoBrowser(withSelectedIndex: selectIndex, urls: urls, parentImageViews: imageViewList)
        present(browserVC, animated: true, completion: nil)
        
        
    }
    //重写父类方法
    override func loadData()
    {
        refreshControl?.beginRefreshing()
        
        self.homePageViewModel.loadStatus(pullUP: self.isPullUp) { (isSuccess,shouldRefresh) in
            self.isPullUp = false
        
            
            if shouldRefresh
            {
                self.tableView?.reloadData()
            }
            
            //结束刷新
            self.refreshControl?.endRefreshing()
        }
    }
    @objc func showFriends()
    {
        let friendVC = CPJFriendViewController()
     
        navigationController?.pushViewController(friendVC, animated: true)
    }
}

extension CPJHomePageViewController
{
    //行数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homePageViewModel.statusList.count
    }
    
    //创建cell
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let viewModel = homePageViewModel.statusList[indexPath.row]
        let cellID = (viewModel.homePageModel.retweeted_status == nil) ? originalCellId : retweetCellId
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CPJHomePageCell
        
        //设置代理
        cell.delegate = self
        
        cell.viewModel = viewModel
        return cell
    }
    //计算行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let viewModel = homePageViewModel.statusList[indexPath.row]
        return viewModel.rowHeight
        
    }
}

//cell的代理方法
extension CPJHomePageViewController: HomePageCellDelegate
{
    //实现cell的代理方法
    func cellDidSelectedURLString(cell: CPJHomePageCell, urlString: String)
    {
        print(urlString)
        //加载网页界面
        let webVC = CPJWebViewController()
        webVC.urlString = urlString
        navigationController?.pushViewController(webVC, animated: true)
    }
}
extension CPJHomePageViewController
{
    //重写父类方法
    override func setUpTableView()
    {
        //调用父类方法
        super.setUpTableView()
        
        //注册nib cell
        tableView?.register(UINib(nibName: "CPJHomePageNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        
        tableView?.register(UINib(nibName: "CPJHomePageRetweetCell", bundle: nil), forCellReuseIdentifier: retweetCellId)
        
        //设置行高 估算行高
        tableView?.estimatedRowHeight = 300
        //自动尺寸
        tableView?.rowHeight = UITableViewAutomaticDimension
        
        //取消分割线
        tableView?.separatorStyle = .none
    }
}

extension CPJHomePageViewController
{
    override func setUpNavigationView()
    {
        //调用父类方法
        super.setUpNavigationView()
        //设置本类属性
        let nickName = CPJNetworkManager.shared.userAccount.screen_name
        
        navitem.leftBarButtonItem = UIBarButtonItem(size: CGSize(width: 40, height: 30), titleStr: "好友", fontSize: 16, target: self, selector:  #selector(showFriends), isBack:false)
        
        let navButton = CPJTitleImageButton(title: nickName)
        navButton.addTarget(self, action: #selector(navigationAction), for: .touchUpInside)
       
        navitem.titleView = navButton
    }
    
    @objc private func navigationAction(navBtn: CPJTitleImageButton)
    {
        let result = navBtn.rightImage.image?.isEqual(UIImage(named: "navigationbar_arrow_up")) ?? false
        
        if (result)
        {
            navBtn.rightImage.image = UIImage(named: "navigationbar_arrow_down")
        }
        else
        {
            navBtn.rightImage.image = UIImage(named: "navigationbar_arrow_up")
        }
    }
}
